<?php
// +----------------------------------------------------------------------
// | 有理想的地方，地狱都是天堂。
// +----------------------------------------------------------------------
// | Copyright @ df81.com 版权所有
// +----------------------------------------------------------------------
// | 作者: 南国老符 邮箱：1062129401@qq.com
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\admin\model\AuthRule as authRuleModel;
use app\admin\model\AuthGroup as authGroupModel;
use app\admin\model\AuthGroupAccess as authGroupAccessModel;
use think\facade\Db;
use think\facade\View;

class AuthGroup extends Base{
    // 新增编辑
    public function edit($id=0){
        if(!request()->isPost()){
            $rs = Db::name('auth_group')->where('id',$id)->find();
            View::assign('rs',$rs);
			
			//会员组（部门级别）
            $authgroupData = getChildSort(Db::name('auth_group')->select());
            View::assign("authGroup",$authgroupData);

            //启用支付的模型：折扣率用
            $moduleWhere[] = ['disabled','=',1]; $moduleWhere[] = ['lang','=',$this->lang];
            $moduleList = Db::name('module')->where($moduleWhere)->field('tabledir,title')->select();
            View::assign('module_list',$moduleList);

            return view();
        }else{
            $authRuleRs = Db::name('auth_rule')->select();
            if(empty($authRuleRs)){
                return json(['code' => 1001, 'msg' => lang('c_add_first').lang('v_auth'), 'data' => array('selectid'=>$selectid)]);
            }

        	/*参数获取*/
        	$title = input('title'); $original_price = input('original_price'); $current_price = input('current_price');
        	$consume_price = input('consume_price'); $consume_score = input('consume_score'); $consume_times = input('consume_times');
        	$discountRateArr = input('discount_rate/a'); $give_score = input('give_score'); $give_price = input('give_price');
        	$level_1 = input('level_1'); $level_2 = input('level_2'); $level_3 = input('level_3');

        	/*参数验证*/
        	//价格正则
        	$preg_price = '/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/';
        	//零和正整数
        	$preg_int = '/^\d+$/';
        	if(mb_strlen($title) < 2){
                return json(['code' => 1002, 'msg' => lang('u_parameter_error'), 'data' => array('title'=>$title)]);
            }
        	if(!preg_match($preg_price,$original_price)){
                return json(['code' => 1003, 'msg' => lang('g_upgrade').' '.lang('v_method').'（'.lang('g_maket_price').'）：'.lang('g_illegal'), 'data' => array('original_price'=>$original_price)]);
            }
        	if(!preg_match($preg_price,$current_price)){
                return json(['code' => 1004, 'msg' => lang('g_upgrade').' '.lang('v_method').' （'.lang('g_price').'）：'.lang('g_illegal'), 'data' => array('current_price'=>$current_price)]);
            }
        	if(!preg_match($preg_price,$consume_price)){
                return json(['code' => 1005, 'msg' => lang('g_total_consume').'（'.lang('shopv_amount').'）：'.lang('g_illegal'), 'data' => array('consume_price'=>$consume_price)]);
            }
        	if(!preg_match($preg_int,$consume_score)){
                return json(['code' => 1006, 'msg' => lang('g_total_consume').'（'.lang('shopv_score').'）：'.lang('g_illegal'), 'data' => array('consume_score'=>$consume_score)]);
            }
        	if(!preg_match($preg_int,$consume_times)){
                return json(['code' => 1007, 'msg' => lang('g_total_consume').'（'.lang('g_bi').'）：'.lang('g_illegal'), 'data' => array('consume_times'=>$consume_times)]);
            }
            /*
            if(empty($discountRateArr)) return json('error:discount');
            foreach ($discountRateArr as $discountRate) {
                if(!preg_match($preg_price,$discountRate)){
                    return json('error:discount');
                    break;
                }
            }
            */
        	if(!preg_match($preg_int,$give_score)){
                return json(['code' => 1008, 'msg' => lang('g_discount_rate').'：'.lang('g_illegal'), 'data' => array('give_score'=>$give_score)]);
            }
        	if(!preg_match($preg_price,$give_price)){
                return json(['code' => 1009, 'msg' => lang('g_upgrade').' '.lang('g_give').' '.lang('shopv_score').'：'.lang('g_illegal'), 'data' => array('give_price'=>$give_price)]);
            }
        	if(!preg_match($preg_price,$level_1)){
                return json(['code' => 1010, 'msg' => lang('g_upgrade').' '.lang('g_give').' '.lang('shopv_balance').'：'.lang('g_illegal'), 'data' => array('level_1'=>$level_1)]);
            }
        	if(!preg_match($preg_price,$level_2)){
                return json(['code' => 1011, 'msg' => lang('g_first_commission_rate').'：'.lang('g_illegal'), 'data' => array('level_2'=>$level_2)]);
            }
        	if(!preg_match($preg_price,$level_3)){
                return json(['code' => 1012, 'msg' => lang('g_second_commission_rate').'：'.lang('g_illegal'), 'data' => array('level_3'=>$level_3)]);
            }
        	if($level_1 + $level_2 + $level_3 > 100){
                return json(['code' => 1013, 'msg' => lang('g_third_commission_rate').'：'.lang('g_illegal'), 'data' => array('level_3'=>$level_3)]);
            }

            try {
                authGroupModel::edit($id);
                return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
            } catch (Exception $e) {
                return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
            }
        }		
	}

    // 列表
    public function index(){
    	$keyword = input('keyword'); $order = ['sequence'=>'desc','id'=>'desc'];
		$rs = authGroupModel::index($this->lang,$keyword,$order);

		View::assign('list',$rs);
		View::assign('total',$rs->total());
		View::assign('lastPage',$rs->lastPage());

        if(request()->isAjax()){
            return view('checklist');
        }else{
            return view();
        }
    }
	
	/*单条删除
    * 返回json值：success成功，error失败
    */
    public function delete_one(){
	    $id = input('id');
	    //不能删除默认会员组
	    if($id == 1){
            return json(['code' => 1001, 'msg' => lang('c_delete_cannot_authgroup'), 'data' => array('id'=>$id)]);
        }
		//有会员属于该用户组，请先变更会员的用户组
		$authGroupAccessRs = Db::name('auth_group_access')->where('group_id',$id)->find();
		if(!empty($authGroupAccessRs)){
            return json(['code' => 1002, 'msg' => lang('c_change_authgroup_first'), 'data' => array('group_id'=>$id)]);
        }
        
        try {
            $authGroup = authGroupModel::find($id);
            $authGroup->delete();
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }	
	
	//批量删除
    public function delete_all(){
		$selectid = input('selectid/a');
        // 请选择要删除的数据
		if(empty($selectid)){
            return json(['code' => 1001, 'msg' => lang('c_delete_check'), 'data' => array('selectid'=>$selectid)]);
        }

        // 不可删除创始会员组
		if(in_array("1",$selectid)){
            return json(['code' => 1002, 'msg' => lang('c_delete_cannot_authgroup'), 'data' => array('selectid'=>$selectid)]);
        }
		
		foreach($selectid as $i => $rs){
		    $id = $selectid[$i];
		    
		    //不能删除默认会员组
	        if($id == 1){
                return json(['code' => 1003, 'msg' => lang('c_delete_cannot_authgroup'), 'data' => array('id'=>$id)]);
            }

		    //有会员属于该用户组，请先变更会员的用户组
		    $authGroupAccessRs = Db::name('auth_group_access')->where('group_id',$id)->find();
		    if(!empty($authGroupAccessRs)){
                return json(['code' => 1004, 'msg' => lang('c_change_authgroup_first'), 'data' => array('group_id'=>$id)]);
            }

            $deleteid[] = $id;
	    }
	    
        try {
            Db::name('auth_group')->delete($deleteid);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('deleteid'=>$deleteid)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }	

	//更新启用
    public function update_status(){
        $data['id'] = input('id'); $data['signid'] = input('value');
        
        try {
            $rs = authGroupModel::update($data);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => $rs]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
	}

	//ajax获取权限值
    public function getrule(){
    	$id = input('id');
    	//权限列表
    	$auth = new \common\Auth(); $auth->check('','');
        $authruleWhere[] = ['parentid','=',0];
	    $authruleWhere[] = ['modulesign','=','web'];
	    $authrule_arr = Db::name('auth_rule')->where($authruleWhere)->order('sequence desc,id desc')->select();

	    //当前权限
	    $authgroupRs = Db::name('auth_group')->where('id',$id)->find();
	    $rules_array = explode(',',$authgroupRs['rules']);

	    View::assign("rules_array", $rules_array);
    	View::assign("authrule_arr", $authrule_arr);

        return view();
	}
}